package com.gxuwz.ssy.common;

import com.gxuwz.ssy.model.User;
import com.gxuwz.ssy.service.impl.RoleServiceImpl;
import com.gxuwz.ssy.service.impl.UserServiceImpl;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserServiceImpl userInfoService;

    @Autowired
    private RoleServiceImpl roleService;


    @Override
    public UserDetails loadUserByUsername(String id)  {
        // 通过用户名从数据库获取用户信息
        User userInfo = userInfoService.query().eq("account",id).one();
        if (userInfo == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 角色集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 角色必须以`ROLE_`开头，数据库中没有，则在这里加
        roleService.getRoleListBy(userInfo.getId()).forEach(e->authorities.add(new SimpleGrantedAuthority(  e.getCode() )));
        return new org.springframework.security.core.userdetails.User(
                userInfo.getAccount(),
                // 放入数据库已经加密密码(使用MD5加密)
                userInfo.getPwd(),
                authorities
        );
    }


}
